import { items, itemscategory } from "@/api/wiki";
import { Effect, Reducer, request, Subscription } from "umi";

export interface ItemProps{
  id: string
  img: string
  dname: string
  qual: string
  cost: string
  desc: string
  notes: string
  attrib: string
  mc: string
  cd: string
  lore: string
  components: string
  created: string
}


export interface ItemState {
  items: any
  itemsCategory: any
}

interface ItemModelType {
  namespace: 'item'
  state: ItemState
  effects: {
    fetch: Effect
  }
  reducers: {
    save: Reducer<ItemState>
  }
  subscriptions: {setup:Subscription}
}

const ItemModel: ItemModelType = {
  namespace: "item",
  state: {
    items: {},
    itemsCategory: {}
  },
  effects: {
    *fetch({type,payload},{put,call}) {
      const data = yield request(items)
      const itemsObj= data['itemdata']

      const category = yield request(itemscategory)
      const itemsCategory = category.result
      
      yield put({
        type: 'save',
        payload: {
          items: itemsObj,
          itemsCategory
        }
      })
    }
  },
  reducers: {
    save: function (state, action): ItemState {
      return {
        ...state,
        ...action.payload
      }
    }
  },
  subscriptions: {
    setup: function ({dispatch, history}): void | Function {
      return history.listen(({ pathname, query }) => {
        if (pathname === '/item') {
          dispatch({
            type: 'fetch'
          })
        }
      })
    }
  }
}
export default ItemModel